html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form Validation</title>
<!-- 引用外部的 CSS 文件來設計表單樣式 -->
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="form-container">
<h1>Register</h1>
<!-- 建立表單,包含名字、姓氏、電子郵件、密碼和確認密碼 -->
<form id="registrationForm" onsubmit="return validateForm()">
<!-- 名字欄位 -->
<label for="first-name">First Name</label>
<input type="text" id="first-name" placeholder="Enter your first name">
JavaScript
// 表單驗證函數
function validateForm() {
// 獲取表單字段
const firstName = document.getElementById('first-name').value.trim();
const lastName = document.getElementById('last-name').value.trim();
const email = document.getElementById('email').value.trim();
const password = document.getElementById('password').value.trim();
const confirmPassword = document.getElementById('confirm-password').value.trim();
const errorMessage = document.getElementById('error-message');
// 清空錯誤消息
errorMessage.textContent = '';
// 驗證名字
if (firstName === '') {
errorMessage.textContent = 'First name is required.';
return false;
}
// 驗證姓氏
if (lastName === '') {
errorMessage.textContent = 'Last name is required.';
return false;
}
// 驗證電子郵件格式
const emailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
if (!emailPattern.test(email)) {
errorMessage.textContent = 'Please enter a valid email address.';
return false;
}
// 驗證密碼長度
if (password.length < 8) {
errorMessage.textContent = 'Password must be at least 8 characters long.';
return false;
}
// 驗證密碼是否匹配
if (password !== confirmPassword) {
errorMessage.textContent = 'Passwords do not match.';
return false;
}
// 如果所有驗證都通過,允許提交表單
return true;
}
CSS
/* 基本頁面樣式 */
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
}
/* 表單容器的樣式 */
.form-container {
background-color: #fff;
padding: 20px;
border-radius: 10px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
width: 300px;
text-align: center;
}
/* 標題樣式 */
h1 {
margin-bottom: 20px;
}
/* 表單輸入框的樣式 */
input[type="text"], input[type="email"], input[type="password"] {
width: 100%;
padding: 10px;
margin-bottom: 10px;
border: 1px solid #ccc;
border-radius: 5px;
box-sizing: border-box;
}
/* 表單按鈕的樣式 */
button {
padding: 10px;
width: 100%;
background-color: #28a745;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
}
button:hover {
background-color: #218838;
}
/* 顯示錯誤信息的樣式 */
#error-message {
margin-top: 10px;
font-size: 14px;
}